package com.fl.mybatisgenerator.controller;


import com.fl.mybatisgenerator.entity.ThreadData;
import com.fl.mybatisgenerator.mapper.ThreadDataMapper;
import com.fl.mybatisgenerator.thread.ThreadPool;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fanlei
 * @since 2022-06-23
 */
@RestController
@RequestMapping("/thread-data")
public class ThreadDataController {
    @Resource
    private ThreadDataMapper mapper;
    private static Random r = new Random();
    //自定义线程池数据
    private final static ExecutorService e = new ThreadPoolExecutor(1000,
            2000, 1, TimeUnit.MINUTES, new SynchronousQueue<>());
    //单例线程模式
    private final static ExecutorService e1 = Executors.newSingleThreadExecutor();
    //缓存模式 消耗内存
    private final static ExecutorService e2 = Executors.newCachedThreadPool();
    //线程数模式 消耗cpu
    private final static ExecutorService e3 = Executors.newFixedThreadPool(10);


    public int sendAllMail() {

        List<CompletableFuture<Boolean>> futureList = new ArrayList<>();
        for (int i = 0; i < 1500; i++) {
            //异步执行sendMaill插入方法，使用自定义线程池
            futureList.add(CompletableFuture.supplyAsync(this::sendMail,e));
        }
        //所有都执行完毕
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();
        AtomicInteger i = new AtomicInteger(0);
        futureList.forEach(x -> {
            try {
                //如果返回值为true 则i加1
                if (x.get()) i.addAndGet(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return i.get();
    }

    public boolean sendMail() {
        for (int i = 0; i < 100; i++) {
            ThreadData threadData = new ThreadData();
            threadData.setMsg("自我循环");
            threadData.setInfo(Thread.currentThread().getName());
            threadData.setName(Thread.currentThread().getName());
            mapper.insert(threadData);
            System.out.println("发生成功:"+threadData.toString());
        }
        return true;
    }

    @RequestMapping("/testflag")
    public String testflag() {
        long start = System.currentTimeMillis();
        System.out.println(sendAllMail());
//        e.shutdown();
        long end = System.currentTimeMillis();
        String res = String.valueOf(end - start);
        return res;
    }

    @RequestMapping("/listinfo")
    public Object listinfo() {
        List<ThreadData> list = mapper.selectList(null);
        return list;
    }
}

